/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.admin;

import com.hboxs.asl.Message;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.entity.Attribute;
import com.hboxs.asl.entity.BaseEntity;
import com.hboxs.asl.entity.Product;
import com.hboxs.asl.entity.ProductCategory;
import com.hboxs.asl.service.AttributeService;
import com.hboxs.asl.service.ProductCategoryService;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Controller - 属性
 */
@Controller("adminAttributeController")
@RequestMapping("/asl-admin/attribute")
public class AttributeController extends BaseController {

    @Resource(name = "attributeServiceImpl")
    private AttributeService attributeService;
    @Resource(name = "productCategoryServiceImpl")
    private ProductCategoryService productCategoryService;

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model) {
        model.addAttribute("productCategoryTree", productCategoryService.findTree());
        model.addAttribute("attributeValuePropertyCount", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT);
        return "/admin/attribute/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Attribute attribute, Long productCategoryId, RedirectAttributes redirectAttributes) {
        for (Iterator<String> iterator = attribute.getOptions().iterator(); iterator.hasNext(); ) {
            String option = iterator.next();
            if (StringUtils.isEmpty(option)) {
                iterator.remove();
            }
        }
        attribute.setProductCategory(productCategoryService.find(productCategoryId));
        if (!isValid(attribute, BaseEntity.Save.class)) {
            return ERROR_VIEW;
        }
        if (attribute.getProductCategory().getAttributes().size() >= Product.ATTRIBUTE_VALUE_PROPERTY_COUNT) {
            addFlashMessage(redirectAttributes, Message.error("admin.attribute.addCountNotAllowed", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT));
        } else {
            attribute.setPropertyIndex(null);
            attributeService.save(attribute);
            addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        }
        return "redirect:list.htm";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("productCategoryTree", productCategoryService.findTree());
        model.addAttribute("attributeValuePropertyCount", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT);
        model.addAttribute("attribute", attributeService.find(id));
        return "/admin/attribute/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Attribute attribute, RedirectAttributes redirectAttributes) {
        for (Iterator<String> iterator = attribute.getOptions().iterator(); iterator.hasNext(); ) {
            String option = iterator.next();
            if (StringUtils.isEmpty(option)) {
                iterator.remove();
            }
        }
        if (!isValid(attribute)) {
            return ERROR_VIEW;
        }
        attributeService.update(attribute, "propertyIndex", "productCategory");
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.htm";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Pageable pageable, ModelMap model) {
		model.addAttribute("page", attributeService.findPage(pageable));
        return "/admin/attribute/listTree";
    }

    /**
	 * 产品分类树
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "/productCategoryTree", method = RequestMethod.GET)
	public void productCategoryTree(HttpServletRequest request,HttpServletResponse response) throws IOException{
		JSONArray tree = productCategoryService.buildProductCategoryTree();
		printJson(response, tree.toString());
	}
	
	/**
	 * 产品分类属性树
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "/attributeTree", method = RequestMethod.GET)
	public void attributeTree(HttpServletRequest request,HttpServletResponse response,Long categoryId) throws IOException{
		ProductCategory pc = productCategoryService.find(categoryId);
		JSONArray tree = attributeService.buildAttributeTree(pc);
		printJson(response, tree.toString());
	}
	
	/**
	 * 产品子属性树
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "/attributeOptionTree", method = RequestMethod.GET)
	public void attributeOptionTree(HttpServletRequest request,HttpServletResponse response,Long attributeId) throws IOException{
		Attribute a = attributeService.find(attributeId);
		JSONArray tree = attributeService.buildAttributeOptionTree(a);
		printJson(response, tree.toString());
	}
	
	/**
	 * 获取JSON格式结果
	 * @param status
	 * @param msg
	 * @param data
	 * @return
	 */
	private  String getJsonResult(String status,String msg,Object data){
		JSONObject result = new JSONObject();
		result.put("status", status);
		result.put("msg", msg);
		result.put("data", data);
		return result.toString();
	}
	
	/**
	 * 删除产品分类
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/removeProductCategory", method = RequestMethod.POST)
	public void removeProductCategory(HttpServletRequest request,HttpServletResponse response,Long paramId) throws IOException{
		
		try {
			ProductCategory productCategory = productCategoryService.find(paramId);
			if (productCategory == null) {
				printJson(response, getJsonResult("ERROR","没有找到此产品分类，请稍后再试",null));
				return ;
			}
			Set<ProductCategory> children = productCategory.getChildren();
			if (children != null && !children.isEmpty()) {
				printJson(response, getJsonResult("ERROR","此分类有子分类，请删除后再操作",null));
				return ;
			}
			Set<Product> products = productCategory.getProducts();
			if (products != null && !products.isEmpty()) {
				printJson(response, getJsonResult("ERROR","此分类有关联产品，请删除后再操作",null));
				return ;
			}
			Set<Attribute> attributes = productCategory.getAttributes();
			if (attributes != null && !attributes.isEmpty()) {
				printJson(response, getJsonResult("ERROR","此分类有子属性，请删除后再操作",null));
				return ;
			}
			
			productCategoryService.delete(paramId);
		} catch (Exception e) {
			e.printStackTrace();
			printJson(response, getJsonResult("OK","删除成功,错误信息："+e.getMessage(),null));
			return;
		}
		printJson(response, getJsonResult("OK","删除成功",null));
		return ;
	}
	
	
	
	/**
	 * 删除商品分类属性
	 * @throws IOException 
	 */
	@RequestMapping(value = "/removeAttribute", method = RequestMethod.POST)
	public void removeAttribute(HttpServletResponse response,Long[] paramId) throws IOException {
		if(paramId == null ){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		try{
			attributeService.delete(paramId);
		}catch(Exception e){
			printJson(response, getJsonResult("OK","删除成功,错误信息："+e.getMessage(),null));
			return;
		}
		
		printJson(response, getJsonResult("OK","删除成功",null));
		return ;
	}
	
	/**
	 * 删除商品分类属性OPTION
	 * @throws IOException 
	 */
	@RequestMapping(value = "/removeAttributeOption", method = RequestMethod.POST)
	public void removeAttributeOption(HttpServletResponse response,Long paramId,String name) throws IOException {
		if(paramId == null || name==null){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		Attribute a = attributeService.find(paramId);
		if(a==null){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		List<String> optionList = a.getOptions();
		for(String o:optionList){
			if(o.equalsIgnoreCase(name)){
				optionList.remove(o);
				a.setOptions(optionList);
				attributeService.update(a);
				break;
			}
		}
		printJson(response, getJsonResult("OK","删除成功",null));
		return ;
	}
	
	/**
	 * 修改商品分类
	 * @throws IOException 
	 */
	@RequestMapping(value = "/editProductCategoryName", method = RequestMethod.POST)
	public void editProductCategoryName(HttpServletResponse response,Long paramId,String newName) throws IOException {
		if(paramId == null || newName == null){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		ProductCategory p = productCategoryService.find(paramId);
		if(p==null){
			printJson(response, getJsonResult("ERROR","非正常参数，请重新操作",null));
			return ;
		}else{
			p.setName(newName);
			productCategoryService.update(p);
		}
		printJson(response, getJsonResult("OK","修改成功",null));
		return ;
	}
	
	/**
	 * 修改商品分类属性
	 * @throws IOException 
	 */
	@RequestMapping(value = "/editAttributeName", method = RequestMethod.POST)
	public void editAttributeName(HttpServletResponse response,Long productCategoryId,Long paramId,String newName) throws IOException {
		if(paramId == null || newName == null){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		
		if(paramId<0){
			if(productCategoryId==null){
				printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
				return ;
			}else{
				ProductCategory p = productCategoryService.find(productCategoryId);
				Set<Attribute> as = p.getAttributes();
				
				Attribute an = new Attribute();
				an.setCreateDate(new Date());
				an.setName(newName);
				if(as==null){
					an.setOrder(1);
					an.setPropertyIndex(1);
				}else{
					an.setOrder(as.size()+1);
					an.setPropertyIndex(as.size()+1);
				}
				an.setProductCategory(p);
				attributeService.save(an);
				printJson(response, getJsonResult("OK","修改成功",an.getId()));
				return ;
			}
			
		}
		Attribute a  = attributeService.find(paramId);
		if(a==null){
			printJson(response, getJsonResult("ERROR","非正常参数，请重新操作",null));
			return ;
		}else{
			a.setName(newName);
			attributeService.update(a);
		}
		printJson(response, getJsonResult("OK","修改成功",a.getId()));
		return ;
	}
	
	/**
	 * 修改商品分类属性OPTION
	 * @throws IOException 
	 */
	@RequestMapping(value = "/editAttributeOptionName", method = RequestMethod.POST)
	public void editAttributeOptionName(HttpServletResponse response,Long attributeId,Long paramId,String name,String newName) throws IOException {
		if(attributeId == null || name == null || newName == null){
			printJson(response, getJsonResult("ERROR","参数不正确，请重新操作",null));
			return ;
		}
		
		Attribute a = attributeService.find(attributeId);
		if(a==null){
			printJson(response, getJsonResult("ERROR","非正常参数，请重新操作",null));
			return ;
		}
		
		List<String> optionList = a.getOptions();
		if(paramId<0){//新增节点
			if(optionList==null){
				optionList = new LinkedList<String>();
			}
			optionList.add(newName);
			a.setOptions(optionList);
			attributeService.update(a);
			printJson(response, getJsonResult("OK","修改成功",null));
			return ;
		}else{
			if(optionList!=null){
				for(int i = 0; i< optionList.size();i++){
					String o = optionList.get(i);
					if(o.equalsIgnoreCase(name)){
						optionList.set(i, newName);
						a.setOptions(optionList);
						attributeService.update(a);
						break;
					}
				}
			}else{
				printJson(response, getJsonResult("ERROR","没有找到此属性，请重新操作",null));
				return ;
			}
		}
		
		printJson(response, getJsonResult("OK","修改成功",null));
		return ;
	}
	
    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Message delete(Long[] ids) {
        attributeService.delete(ids);
        return SUCCESS_MESSAGE;
    }

}